package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.LinearLayout
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCustomItemClick
import com.compass.doctor.databinding.ActivityHospitalizationCertificateBinding
import com.compass.doctor.ui.patient.adapter.InpatientPopupAdapter
import com.compass.doctor.ui.patient.viewmodel.ExamineViewModel
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.doctor.ui.prescription.DiagnoseActivity
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_ORDER_ID
import com.compass.framework.constant.KEY_PATIENT_ID
import com.compass.framework.constant.KEY_SESSION_ID
import com.compass.framework.ext.onClick
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.model.CreateHospitalized
import com.compass.framework.model.Diagnosis
import com.compass.framework.model.InpatientWard
import com.compass.framework.utils.MoneyInputFilter
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getDrawableResource


/**
 * Description： 创建住院证
 * Date:2023/12/19 16:00
 */
class HospitalizationCertificateActivity :
    BaseVBActivity<ActivityHospitalizationCertificateBinding>() {
    private val examineViewModel: ExamineViewModel by viewModels()
    private val patientViewModel: PatientViewModel by viewModels()

    private var inpatientChild: ArrayList<InpatientWard> = ArrayList()//病房（病区child）
    private var conditionList: ArrayList<InpatientWard> = ArrayList()//入院情况
    private lateinit var listPopupWindow: ListPopupWindow
    private lateinit var popupAdapter: InpatientPopupAdapter

    private var windowType = 2//弹出pop类型1.科室  2.病房 3.入院情况
    private lateinit var patientId: String//患者ID
    private lateinit var sessionId: String//患者云信id
    private var inpatientWardName: String? = null

    private var inpatientWard: InpatientWard? = null//接收返回科室
    private var diagnosis: Diagnosis? = null//接收返回的诊断数据/检验检查
    private var hospitalizedDepartmentCode: String? = null
    private var inpatientWardCode: String? = null
    private var diagnosisId: String? = null
    private var hospitalizedConditionId: String? = null


    //诊断回调
    private val mActivityResultLauncherDiagnosis: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    diagnosis = intent.serializable("diagnosis")
                    mBinding.tvDiagnose.text = diagnosis?.name
                    diagnosisId = diagnosis?.id
                }
            }
        }

    //诊断回调
    private val mActivityResultLauncherDepartment: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    inpatientWard = intent.serializable("department")
                    inpatientWard?.let { department ->
                        mBinding.tvDepartment.text = department.name
                        hospitalizedDepartmentCode = department.id
                        inpatientChild=department.child
                        if (inpatientChild.size > 0) {
                            //重置病区数据
                            setInpatientWard(inpatientChild[0])
                        }

                    }


                }
            }
        }

    companion object {
        fun start(context: Context, patientId: String, sessionId: String,orderId:String) {
            val intent = Intent(context, HospitalizationCertificateActivity::class.java)
            intent.putExtra(KEY_PATIENT_ID, patientId)
            intent.putExtra(KEY_SESSION_ID, sessionId)
            intent.putExtra(KEY_ORDER_ID, orderId)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        initPopupWindow()

        val filter = MoneyInputFilter()
        mBinding.advanceMoney.filters = arrayOf(filter)


    }

    override fun initData() {
        patientId = intent.serializable(KEY_PATIENT_ID)!!
        sessionId = intent.serializable(KEY_SESSION_ID)!!
        showLoading()
//        examineViewModel.getInpatientWardList()
//        examineViewModel.inpatientLiveData.observe(this) {
//            it?.let {
//                inpatientList = it as ArrayList<InpatientWard>
//            }
//            dismissLoading()
//        }
        patientViewModel.getPatientDetails(patientId)
        patientViewModel.patientDetailsLiveData.observe(this) {
            it?.let {
                mBinding.ivHead.setUrlCircle(it.avatar)
                mBinding.tvName.text = it.name
                mBinding.ivSex.background =
                    if (it.sex == 1) getDrawableResource(R.mipmap.icon_male) else getDrawableResource(
                        R.mipmap.icon_female
                    )
                mBinding.tvAge.text = it.patientAge

            }
            dismissLoading()
        }
        examineViewModel.conditionLiveData.observe(this) {
            it?.let {
                conditionList = it as ArrayList<InpatientWard>
                initCondition()
            }
        }
        examineViewModel.createHospitalizedLiveData.observe(this) {
            dismissLoading()
            it?.let {
                val diagnosisName = diagnosis?.name

                showToast("开具成功")
                finish()
            }
        }
        0
    }

    override fun intListener() {

        popupAdapter.setOnCustomItemClick(object : OnCustomItemClick {
            override fun onItemCallBack(position: Int, value: String, label: String) {

                when (windowType) {
//                    1 -> {
//                        inpatientChild = searchList[position].child
//                        isOnClick.set(true)
//                        mBinding.edtDiagnosis.setText(searchList[position].name)
//                        mBinding.edtDiagnosis.setSelection(searchList[position].name.length)
//                        hospitalizedDepartmentCode = searchList[position].id
//                        if (inpatientChild.size > 0) {
//                            //重置病区数据
//                            setInpatientWard(inpatientChild[0])
//                        }
//                    }

                    2 -> {
                        setInpatientWard(inpatientChild[position])
                    }

                    3 -> {
                        mBinding.tvCondition.text = conditionList[position].name
                        hospitalizedConditionId = conditionList[position].id
                    }
                }
                listPopupWindow.dismiss()
            }
        })
        mBinding.tvDepartment.onClick {

            val intent = Intent(this, InpatientDepartmentActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, "2")
            mActivityResultLauncherDepartment?.launch(intent)

        }


        mBinding.tvSickroom.onClick {
            if (inpatientChild.isNotEmpty()) {
                initSickroom()
            } else {
                showToast("请先选择科室")
            }
        }
        mBinding.tvDiagnose.onClick {
            val intent = Intent(this, DiagnoseActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, "2")
            mActivityResultLauncherDiagnosis?.launch(intent)
        }
        mBinding.tvCondition.onClick {
            examineViewModel.getConditionList()
        }
        mBinding.tvSubmit.onClick {
            createHospitalized()
        }
    }

    private fun setInpatientWard(inpatientWard: InpatientWard) {
        inpatientWardCode = inpatientWard.id
        inpatientWardName = inpatientWard.name
        mBinding.tvSickroom.text = inpatientWardName
    }


    private fun createHospitalized() {
        if (hospitalizedDepartmentCode.isNullOrEmpty()) {
            showToast("请选择科室")
            return
        }
        if (inpatientWardCode.isNullOrEmpty()) {
            showToast("请选择病区")
            return
        }

        if (diagnosisId.isNullOrEmpty()) {
            showToast("请选择诊断")
            return
        }
        val advancePrice = mBinding.advanceMoney.text.toString().trim()
        if (advancePrice.isNullOrEmpty()) {
            showToast("请选输入预缴金额")
            return
        }

        if (hospitalizedConditionId.isNullOrEmpty()) {
            showToast("请选择入院情况")
            return
        }
        val remark = mBinding.tvRemark.text.toString().trim()

        val createHospitalized = CreateHospitalized(
            hospitalizedConditionId,
            patientId,
            hospitalizedDepartmentCode,
            inpatientWardCode,
            inpatientWardName,
            advancePrice,
            diagnosisId,
            remark
        )
        showLoading()
        examineViewModel.createHospitalized(createHospitalized)

    }


    private fun initPopupWindow() {
        listPopupWindow = ListPopupWindow(this)
        popupAdapter = InpatientPopupAdapter(this)
        listPopupWindow.setAdapter(popupAdapter)
        listPopupWindow.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow.isModal = true
        val bgDrawable = ContextCompat.getDrawable(
            this,
            R.drawable.ps_permission_desc_bg
        )
        listPopupWindow.setBackgroundDrawable(bgDrawable)


    }


//    private fun initDepartments() {
//        windowType = 1
//        listPopupWindow.anchorView = mBinding.edtDiagnosis
//        popupAdapter.setList(searchList)
//        listPopupWindow.show()
//
//    }

    private fun initSickroom() {
        windowType = 2
        popupAdapter.setList(inpatientChild)
        listPopupWindow.anchorView = mBinding.tvSickroom
        listPopupWindow.show()
    }

    private fun initCondition() {
        windowType = 3
        popupAdapter.setList(conditionList)
        listPopupWindow.anchorView = mBinding.tvCondition
        listPopupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow.show()
    }
}